<template>
  <div class="top-left-cmp" style="height:100%">
    <!--  计划完成情况   -->
    <div>
      <div class="dc-left">
        <div class="dc-text">
          计划完成率
          <dv-decoration3 style="width: 200px; height: 20px" />
        </div>
      </div>
      <div style="display: flex; width: 100%">
        <div style="width: 100%; height: 320px">
          <div id="PlanCharts" style="width:100%;height:100%;"></div>
        </div>
      </div>
    </div>
    <div style="height: calc((100% - 407px) / 2)">
      <div class="dc-left">
        <div class="dc-text">
          本月在产情况
          <dv-decoration3 style="width: 200px; height: 20px" />
        </div>
      </div>
      <div style="display: flex; width: 100%;height:calc(100% - 87px);">
        <div style="width: 100%; height:100%;">
          <div id="mouthCharts" style="width:100%;height:calc(100% + 10px);"></div>
        </div>
      </div>
    </div>
    <div style="height: calc((100% - 407px) / 2)">
      <div class="dc-left">
        <div class="dc-text">
          跨月在产情况
          <dv-decoration3 style="width: 200px; height: 20px" />
        </div>
      </div>
      <div style="display: flex; width: 100%;height:calc(100% - 87px);">
        <div style="width: 100%; height:100%">
          <div id="nextMouthCharts" style="width:100%;height:calc(100% + 10px);"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, defineExpose} from 'vue';
import {listPlanFinishRate, listPlanSituation} from "../../../../apis/mes/borad";
import * as echarts from 'echarts/core';
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent
} from 'echarts/components';
import {
  BarChart,
  GaugeChart
} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';

echarts.use([
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent, // 添加单轴组件
  BarChart,
  GaugeChart,
  CanvasRenderer
]);

const props = defineProps({
  year: {
    type: Number,
    required: true
  }
});
// 项目配置处理
const getBoardConfig = ref({
      itntervalTime: 1000 * 60 * 10, // 默认10分钟
      startDate: '',
      endDate: ''
    }
);

// 响应式数据
const color = ref(["#07a6ff", "#3ddef5", "#f99b8e", "#7cd6cf", "#9192ab", "#4a73e2", "#7898e1"]);
const planOptions = ref({});
const mouthOptions = ref({});
const nextMouthOptions = ref({});

// 图表实例
const planChart = ref(null);
const mouthChart = ref(null);
const nextMouthChart = ref(null);

// 配置参数
const params = ref({
  startTime: '',
  endTime: ''
});

// 其他变量
const timers = ref([]);
const interval = ref(null);
const hasCalledApi = ref(false);

onMounted(() => {
  onMountedHandler()
})
const onMountedHandler = () => {
  hasCalledApi.value = true;
  let yearVal = props.year;
  listPlanFinish(yearVal);

  let mouthCharts = echarts.init(document.getElementById('mouthCharts'));
  proMouth(mouthCharts, yearVal);

  let nextMouthCharts = echarts.init(document.getElementById('nextMouthCharts'));
  proNextMouth(nextMouthCharts, yearVal);

  interval.value = setInterval(function () {
    timers.value.forEach(item => {
      clearInterval(item);
    });
    proMouth(mouthCharts, yearVal);
    proNextMouth(nextMouthCharts, yearVal);
  }, 1000 * 60 * 10);

};
// 计划完成率
const listPlanFinish = (yearVal) => {
  const requestParams = {
    year: yearVal,
    ...params.value
  };
  listPlanFinishRate(requestParams).then((data) => {
    let gaugeData = [[], [], []];
    gaugeData = data;
    let offsetCenter = -90;
    let detailOffset = -75;
    gaugeData = gaugeData.map((item, i) => {
      offsetCenter += 43;
      detailOffset += 43;
      return {
        value: item.value,
        name: "本" + item.name,
        title: {
          offsetCenter: ['0%', offsetCenter + '%']
        },
        detail: {
          valueAnimation: true,
          color: ["#07a6ff", "#80FFA5", '#fac858', "#9192ab", "#FC8452"][i],
          offsetCenter: ['0%', detailOffset + '%'],
          formatter: function (value) {
            return item.finish + '/' + item.total + '   ' + value.toFixed(1) + '%';
          }
        }
      };
    });
    planOptions.value = {
      color: ["#07a6ff", "#80FFA5", '#fac858', "#9192ab", "#FC8452"],
      tooltip: {
        trigger: 'item',
        formatter: '{b} : {c}%'
      },
      series: [
        {
          type: 'gauge',
          startAngle: 90,
          endAngle: -270,
          center: ['50%', '50%'], // 默认全局居中
          radius: '100%',
          anchor: {
            show: false,
            showAbove: false
          },
          axisLabel: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: { // 分隔线
            lineStyle: {
              color: 'transparent', //分割线
              shadowColor: '#fff' //默认透明
            }
          },
          pointer: {
            show: false
          },
          progress: {
            show: true,
            overlap: false,
            roundCap: true,
            clip: false,
          },
          axisLine: {
            roundCap: false,
            lineStyle: {
              width: 30,
              color: [[1, '#002C51']]
            }
          },
          data: gaugeData,
          title: {
            color: '#ffffff',
            offsetCenter: ['0%', '0']
          },
          /*itemStyle: {
            color: '#07a6ff',
            lineStyle: {
              width: 20
            },
            shadowColor: '#07a6ff80',
            shadowBlur: 10,
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },*/
          detail: {
            width: '100%',
            height: 14,
            fontSize: 14,
            //formatter: '{value}%'
          }
        }
      ]
    };
    let PlanCharts = echarts.init(document.getElementById('PlanCharts'));
    PlanCharts.setOption(planOptions.value);

    setInterval(function () {
      const _params = {
        year: yearVal,
        ...params.value
      };
      listPlanFinishRate(_params).then((newres) => {
        gaugeData[0].value = newres[0].value;
        gaugeData[1].value = newres[1].value;
        gaugeData[2].value = newres[2].value;
        PlanCharts.setOption({
          series: [
            {
              data: gaugeData,
              pointer: {
                show: false
              }
            }
          ]
        });
      });
    }, 60000 * 10);
  });
};

// 本月在产情况
const proMouth = (mouthCharts, yearVal) => {
  //monthFlag=true 本月
  //monthFlag=false 下月
  const requestParams = {
    year: yearVal,
    monthFlag: true,
    ...params.value
  };
  listPlanSituation(requestParams).then((newData) => {
    let data = {
      "series": {
        "未开工": [],
        "执行中": [],
        "已完工": [],
        "已入库": [],
        "停工": []
      },
      sumTotal: [],
      sumData: [],
      "yAxis": []
    };
    newData.forEach((item) => {
      data.yAxis.push(item.pdmProductName);
      data.series["未开工"].push(item.noStartTotal);
      data.series["执行中"].push(item.inProgressTotal);
      data.series["已完工"].push(item.finishTotal);
      data.series["已入库"].push(item.receivedTotal);
      data.series["停工"].push(item.suspendedTotal);
      data.sumTotal.push(item.sumTotal);
      data.sumData.push(0);

    });
    let serises = [];
    for (let i in data.series) {
      const borderRadius = i == Object.keys(data.series).pop() ? 20 : 0;
      serises.push({
        name: i,
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          formatter: function (p) {
            if (p.data && p.data != 0) {
              return p.data;
            } else {
              return '';
            }
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data.series[i],
        itemStyle: {
          borderRadius: [0, borderRadius, borderRadius, 0]
        }
      });
    }
    serises.push({
      name: '合计',
      type: 'bar',
      stack: 'total',
      label: {
        show: true,
        position: 'right',
        textStyle: {
          color: '#fff'
        },
        formatter: function (p) {
          let sum = data.sumTotal[p.dataIndex];
          return sum;
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: data.sumData
    });
    const maxShow = 5;// 一次性展示6个。
    mouthOptions.value = {
      color: ["#9192ab", "#3da1fd", '#a7ffa7', "#07f107", "#ee3223"],
      legend: {
        bottom: 10,
        data: Object.keys(data.series),
        textStyle: {
          color: '#fff'
        }
      },
      tooltip: {},
      grid: {
        top: 0,
        left: '20',
        right: '20',
        bottom: '30',
        containLabel: true
      },
      dataZoom: [//滑动条
        {
          yAxisIndex: 0,//这里是从X轴的0刻度开始
          show: false,//是否显示滑动条，不影响使用
          type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
          startValue: 0, // 从头开始。
          endValue: maxShow
        }
      ],
      xAxis: {
        show: false,
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: data.yAxis,
        inverse: true, //是否是反向坐标轴
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisTick: {
          show: false,
        },
      },
      series: serises
    };

    mouthCharts.setOption(mouthOptions.value);

    if (data.sumTotal.length > maxShow + 1) {
      let timer = setInterval(function () {
        // 每次向后滚动一个，最后一个从头开始。
        if (mouthOptions.value.dataZoom[0].endValue + 1 == data.sumTotal.length) {
          mouthOptions.value.dataZoom[0].endValue = maxShow;
          mouthOptions.value.dataZoom[0].startValue = 0;
        } else {
          mouthOptions.value.dataZoom[0].endValue = mouthOptions.value.dataZoom[0].endValue + 1;
          mouthOptions.value.dataZoom[0].startValue = mouthOptions.value.dataZoom[0].startValue + 1;
        }
        mouthCharts.setOption(mouthOptions.value);
      }, 3000);
      timers.value.push(timer);
    }
  });
};

// 下月在产情况
const proNextMouth = (nextMouthCharts, yearVal) => {
  const requestParams = {
    year: yearVal,
    monthFlag: false,
    ...params.value
  };
  listPlanSituation(requestParams).then((newData) => {
    let data = {
      "series": {
        "未开工": [],
        "执行中": [],
        "已完工": [],
        "已入库": [],
        "停工": []
      },
      sumTotal: [],
      sumData: [],
      "yAxis": []
    };
    newData.forEach((item) => {
      data.yAxis.push(item.pdmProductName);
      data.series["未开工"].push(item.noStartTotal);
      data.series["执行中"].push(item.inProgressTotal);
      data.series["已完工"].push(item.finishTotal);
      data.series["已入库"].push(item.receivedTotal);
      data.series["停工"].push(item.suspendedTotal);
      data.sumTotal.push(item.sumTotal);
      data.sumData.push(0);

    });
    let serises = [];
    for (let i in data.series) {
      const borderRadius = i == Object.keys(data.series).pop() ? 20 : 0;
      serises.push({
        name: i,
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          formatter: function (p) {
            if (p.data && p.data != 0) {
              return p.data;
            } else {
              return '';
            }
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data.series[i],
        itemStyle: {
          borderRadius: [0, borderRadius, borderRadius, 0]
        }
      });
    }
    serises.push({
      name: '合计',
      type: 'bar',
      stack: 'total',
      label: {
        show: true,
        position: 'right',
        textStyle: {
          color: '#fff'
        },
        formatter: function (p) {
          let sum = data.sumTotal[p.dataIndex];
          return sum;
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: data.sumData
    });
    const maxShow = 5;// 一次性展示6个。
    nextMouthOptions.value = {
      color: ["#9192ab", "#3da1fd", '#a7ffa7', "#07f107", "#ee3223"],
      legend: {
        bottom: 10,
        data: Object.keys(data.series),
        textStyle: {
          color: '#fff'
        }
      },
      tooltip: {},
      grid: {
        top: 0,
        left: '20',
        right: '20',
        bottom: '30',
        containLabel: true
      },
      dataZoom: [//滑动条
        {
          yAxisIndex: 0,//这里是从X轴的0刻度开始
          show: false,//是否显示滑动条，不影响使用
          type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
          startValue: 0, // 从头开始。
          endValue: maxShow
        }
      ],
      xAxis: {
        show: false,
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: data.yAxis,
        inverse: true, //是否是反向坐标轴
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisTick: {
          show: false,
        },
      },
      series: serises
    };
    nextMouthCharts.setOption(nextMouthOptions.value);

    if (data.sumTotal.length > maxShow + 1) {
      let that = this;

      let timer = setInterval(function () {
        // 每次向后滚动一个，最后一个从头开始。
        if (nextMouthOptions.value.dataZoom[0].endValue + 1 == data.sumTotal.length) {
          nextMouthOptions.value.dataZoom[0].endValue = maxShow;
          nextMouthOptions.value.dataZoom[0].startValue = 0;
        } else {
          nextMouthOptions.value.dataZoom[0].endValue = nextMouthOptions.value.dataZoom[0].endValue + 1;
          nextMouthOptions.value.dataZoom[0].startValue = nextMouthOptions.value.dataZoom[0].startValue + 1;
        }
        nextMouthCharts.setOption(nextMouthOptions.value);
      }, 3000);
      timers.value.push(timer);
    }
  });
};

onBeforeUnmount(() => {
  timers.value.forEach(item => {
    clearInterval(item);
  });
  if (interval.value) {
    clearInterval(interval.value); // 在Vue实例销毁前，清除时间定时器
  }
});

defineExpose({
  onMountedHandler
})
</script>

<style lang="scss" scoped>
.top-left-cmp {
  width: 28% !important;
  height: 100%;

  .dc-left {
    width: 100%;
  }

  .dc-text {
    display: flex;
    flex-direction: column;
    height: 10%;
    font-size: 20px;
    padding: 20px;
    box-sizing: border-box;
  }

  .dc-left .dc-text {
    align-items: flex-start;
    justify-content: center;
  }

  .main-value {
    font-weight: bold;
    font-size: 30px;

    span {
      font-size: 50px;
      color: #00c0ff;
      margin-right: 15px;
    }
  }

  .compare-value {
    height: 35px;
    line-height: 35px;
    font-size: 18px;

    span {
      margin-right: 30px;
    }
  }
}
</style>
